package org.cainiao.io.nio.channel;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.GatheringByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class Marketing {

    private static final String DEMOGRAPHIC = "blahblah.txt";

    // "利用分而治之的方法论"
    public static void main(String[] argv) throws Exception {
        int reps = 10;
        if (argv.length > 0) {
            reps = Integer.parseInt(argv[0]);
        }
        FileOutputStream fos = new FileOutputStream(DEMOGRAPHIC);
        GatheringByteChannel gatherChannel = fos.getChannel();
        // 生成一些出色的市场营销传播内容，额，可再利用的内容
        ByteBuffer[] bs = utterBS(reps);
        // 将消息传达给等待中的市场
        while (gatherChannel.write(bs) > 0) {
            // 空的循环体
            // 循环直到 write() 返回 0
        }
        System.out.println("Mindshare paradigms synergized to " + DEMOGRAPHIC);
        fos.close();
    }

    // ------------------------------------------------
    // These are just representative; add your own
    private static final String[] COL_1 = {
        "Aggregate", "Enable", "Leverage",
        "Facilitate", "Synergize", "Repurpose",
        "Strategize", "Reinvent", "Harness"
    };
    private static final String[] COL_2 = {
        "cross-platform", "best-of-breed", "frictionless",
        "ubiquitous", "extensible", "compelling",
        "mission-critical", "collaborative", "integrated"
    };
    private static final String[] COL_3 = {
        "methodologies", "infomediaries", "platforms",
        "schemas", "mindshare", "paradigms",
        "functionalities", "web services", "infrastructures"
    };
    private static final String NEW_LINE = System.getProperty("line.separator");

    // The Marcom-atic 9000
    private static ByteBuffer[] utterBS(int howMany) {
        List<ByteBuffer> list = new LinkedList<>();
        for (int i = 0; i < howMany; i++) {
            list.add(pickRandom(COL_1, " "));
            list.add(pickRandom(COL_2, " "));
            list.add(pickRandom(COL_3, NEW_LINE));
        }
        ByteBuffer[] bufs = new ByteBuffer[list.size()];
        list.toArray(bufs);
        return bufs;
    }

    // 传媒总监
    private static final Random RAND = new Random();

    // Pick one, make a buffer to hold it and the suffix, load it with
    // the byte equivalent of the strings (will not work properly for
    // non-Latin characters), then flip the loaded buffer so it's ready
    // to be drained
    private static ByteBuffer pickRandom(String[] strings, String suffix) {
        String string = strings[RAND.nextInt(strings.length)];
        int total = string.length() + suffix.length();
        ByteBuffer buf = ByteBuffer.allocate(total);
        buf.put(string.getBytes(StandardCharsets.US_ASCII));
        buf.put(suffix.getBytes(StandardCharsets.US_ASCII));
        buf.flip();
        return buf;
    }

}
